﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Text.RegularExpressions;


namespace CCPSIP.SIP
{
    /// <summary>CCPSIP_022：設定桌機共振+轉接 API</summary>
    /// idHeader = 裝置 UUID 前八碼。iOS 請使用 [CCPCrypto getIdHeader] 呼叫。
    /// checkcode = 裝置限時驗證碼。iOS 請使用 [CCPCrypto getCheckcode] 呼叫。
    /// action = 設定動作:共振或轉接。('Fork', 'Forward')
    /// target = 設定目標值。('Y', 'N', 或轉接號碼)

    public class fork_save : IHttpHandler
    {
        private const string kHQMobileExtPattern = "^" + SipKit.kHQMobileExtPrefix + "[1-9][0-9]{2}$";


        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";

            try
            {
                //【01】取得POST參數，驗證身分
                //
                string idHeader = req.Form["idHeader"];
                string checkcode = req.Form["checkcode"];
                string action = req.Form["action"];//設定動作:共振或轉接
                string target = req.Form["target"];//設定目標值:Y/N或轉接號碼

                SipUserInfo userInfo = SipKit.GetUserInfo(idHeader, checkcode, req);
                if (userInfo == null)
                {
                    throw new Exception("Error_01: Cannot identify this device");//無法識別此裝置
                }


                //【02】檢查是否可設定共振
                //
                if (!Regex.IsMatch(userInfo.SIP_Num, kHQMobileExtPattern))
                {
                    throw new Exception("Error_02: You have no access right");//沒有存取權限
                }


                //【03】取得IP PBX設定
                //
                string HQDesktopExt = SipKit.getHQDesktopExt(userInfo.SIP_Num);
                Dictionary<string, string> UserDict = IPPbxKitV2.GetUserData(HQDesktopExt);
                List<string> forkList = new List<string>(3);
                forkList.Add(UserDict["forkphone1"]);//共振號碼1
                forkList.Add(UserDict["forkphone2"]);//共振號碼2
                forkList.Add(UserDict["forkphone3"]);//共振號碼3


                //【04】調整共振轉接設定
                //
                if (action == "Forward")
                {
                    if (string.IsNullOrEmpty(target))
                    {
                        //【04-1】轉接:關
                        //
                        UserDict["cfphone"] = "";
                    }
                    else
                    {
                        //【04-2】轉接:開
                        //
                        if (!Regex.IsMatch(target, "^[0-9]{3,11}$"))
                        {
                            throw new Exception("Error_03: Forwarding number is wrong");//轉接號碼錯誤
                        }

                        const string kCallOutPrefix = "0";

                        if (Regex.IsMatch(target, "^09[0-9]{8}$"))//手機號碼
                            target = kCallOutPrefix + target;
                        else if (Regex.IsMatch(target, "^02[1-9][0-9]{7}$"))//北北基電話(有加02)
                            target = kCallOutPrefix + target.Remove(0, 2);
                        else if (Regex.IsMatch(target, "^[1-9][0-9]{7}$"))  //北北基電話(沒加02)
                            target = kCallOutPrefix + target;
                        else if (Regex.IsMatch(target, "^0[3-8][0-9]{6}$")) //台灣其他縣市電話
                            target = kCallOutPrefix + target;

                        UserDict["cfphone"] = target;
                    }
                }
                else if (action == "Fork")
                {
                    UserDict["cfphone"] = "";

                    if (target == "Y")
                    {
                        //【04-3】共振:開
                        //
                        if (!forkList.Contains(userInfo.SIP_Num))
                        {
                            if (string.IsNullOrEmpty(UserDict["forkphone1"]))
                                UserDict["forkphone1"] = userInfo.SIP_Num;
                            else if (string.IsNullOrEmpty(UserDict["forkphone2"]))
                                UserDict["forkphone2"] = userInfo.SIP_Num;
                            else
                                UserDict["forkphone3"] = userInfo.SIP_Num;
                        }
                    }
                    else
                    {
                        //【04-4】共振:關
                        //
                        for (int i = 1; i <= 3; i++)
                        {
                            string forkKey = "forkphone" + i;
                            if (UserDict[forkKey] == userInfo.SIP_Num)
                                UserDict[forkKey] = "";
                        }
                    }
                }
                else
                {
                    throw new Exception("Error_04: Invalid action");//無效的動作
                }


                //【05】設定值存檔
                //
                IPPbxKitV2.UpdateUser(UserDict);


                //【06】取得桌機共振資訊
                //
                Dictionary<string, string> resultDict = SipKit.getForkInfo(userInfo.SIP_Num);


                //【99】回傳結果
                //
                resp.ContentType = "application/json";
                resp.Charset = null;
                fastJSON.JSON.Instance.Parameters.EnableAnonymousTypes = true;
                resultStr = fastJSON.JSON.Instance.ToJSON(resultDict);
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                resultStr = ChrisKit.Ex2Xml(ex, false);
            }
            finally
            {
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
                resp.Flush();
                resp.Close();
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}
